package com.iwop.moto.controller.weixin;

import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.Comm;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.controller.BaseController;
import com.iwop.moto.model.FPrizeUser;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.FPrizeUserService;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.iwop.moto.utils.weixin.utils.EmojiFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liuwb on 2016/11/16.
 */

@Controller
public class WxDialController extends BaseController {

    @Autowired
    private FPrizeUserService fPrizeUserService;

    /**
     * 中奖用户名单
     * */
    @RequestMapping(value="/api/wx/prize/index")
    @LoginAuth(isWx = true)
    public ModelAndView ApiWxPrizeIndex(HttpServletRequest request,HttpServletResponse response) throws IOException {
        SuperRecordModel wxInfo =(SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID); // (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
         //wxInfo.put("openid","11111111111111111111");
      /*      Map wxAccessToken = getWxAccessToken();
            String wxAttentionUser = WeixinUtil.getWxAttentionUser(wxAccessToken.get("access_token").toString(),null);
            if(wxAttentionUser.indexOf(wxInfo.getString("openid"))<0){//用户未关注
                response.sendRedirect("http://mp.weixin.qq.com/s/MtGEIJQWlzm_zsIVTXa8OQ");
                return null;
            }*/
        FPrizeUser prizeParam = new FPrizeUser();
        Long countNum = exsitPrize(prizeParam,wxInfo);
        if(countNum>0){
            FPrizeUser prizeCode = fPrizeUserService.findPrizeByOpenId(wxInfo.getString("openid"));
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
            response.sendRedirect("/api/wx/accept?prizeCode="+prizeCode.getPrizeCode()+"&type="+prizeCode.getDialCode()+"&isNew=1");
            return null;
        }
        List<SuperRecordModel> srm=fPrizeUserService.findPrizeSuccess();
        ModelAndView mv = new ModelAndView();
        mv.addObject("ticket",getWxTicket().get("ticket"));
        mv.addObject("prizeList", srm);
        mv.addObject("countNum", countNum);
        mv.setViewName("weixin/prize/index");
        return  mv;
    }

    /**
     *
     * */
    @RequestMapping(value="/api/wx/accept")
    @ResponseBody
    @LoginAuth(isWx = true)
    public ModelAndView ApiWxaccept(HttpServletRequest request){
        SuperRecordModel wxInfo =(SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
        String prizeCode = request.getParameter("prizeCode");
        String type = request.getParameter("type");
        ModelAndView mv=new ModelAndView();
        mv.addObject("nickname",wxInfo.get("nickname"));
        mv.addObject("ticket",getWxTicket().get("ticket"));
        mv.addObject("prizeCode",prizeCode);
        mv.addObject("type",type);
        mv.setViewName("weixin/prize/accept");
        return mv;
    }

    /**
     * 兑奖确定接口
     * */
    @RequestMapping(value="/api/wx/cash/prize")
    @ResponseBody
    @LoginAuth(isWx = true)
    public ResultModel ApiWxCashPrize(){
    try {
        SuperRecordModel srModel = this.getSRModel();
        SuperRecordModel superRecordModel=fPrizeUserService.findPrizeCode(srModel);
        if (superRecordModel==null ){
            return getErr(ErrCode.ERROR_PRIZE_CODE);
        }else if (superRecordModel.getString("prize_flag").equals("1")){
            return getErr(ErrCode.REPEAT_PRIZE_CODE);
        }
        FPrizeUser fPrizeUser=new FPrizeUser();
        fPrizeUser.setPrizeId(superRecordModel.getString("prize_id"));
        fPrizeUser.setPrizeFlag("1");
        fPrizeUser.setPrizeTime(new Date());
        fPrizeUserService.update(fPrizeUser);
        return getSucceed(superRecordModel,ErrCode.SUCCEED);
    }catch (Exception e){
        return getErr(ErrCode.ERROR_SYSTEM);
    }
    }

    /**
     * @说明: 【Again 再来一次 | Helmet 头盔 | Glove 手套】
     * 抽奖规则 每一个关注用户只能中奖一个【头盔 or 手套】 最多有3次抽奖机会
     *         第一次用户抽奖默认抽到再来一次
     *         第二次有50%抽中再来一次 10%抽中头盔 40%抽中手套 (抽中则停止)
     *         第三次一定抽中 20%抽中头盔 80%抽中手套
     */
    @RequestMapping(value="/api/wx/dial/extract")
    @LoginAuth(isWx = true)
    @ResponseBody
    public ResultModel apiWxDialExtract(HttpServletResponse response){
        try{
            SuperRecordModel wxInfo =(SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID); // (SuperRecordModel)getSession().getAttribute(Comm.SESSION_WEIXIN_ID);
           /* wxInfo.put("openid","11111111111111111111");
            wxInfo.put("nickname","测试数据");*/
            Map result = new HashMap<>();
            FPrizeUser prizeParam = new FPrizeUser();
            Long countNum = exsitPrize(prizeParam,wxInfo);
            if(countNum>=1){
                return getErr("您已经抽过奖!");
            }
            prizeParam.setStatusFlag("0");//非有效 1正常 0逻辑删除
            prizeParam.setDialCode("Again");//再来一次
            Long prizeNum = fPrizeUserService.findPrizeCountByParams(prizeParam);
            int again = (int)(Math.random()*100)>50?2:1;
            String openid = wxInfo.getString("openid");
            String name = EmojiFilter.filterEmoji(wxInfo.getString("nickname"));
            FPrizeUser glove =null;
            if(prizeNum.intValue()<=0){//第一次一定不中 默认再来一次
                AgainPrize(openid,name);//再来一次
                result.put("dialCode", "Again"+again);
                return getSucceed(result);
            } else if(prizeNum.intValue()<=1){
                int rn = (int)(Math.random()*100);
                if(rn<=50){ //百分之50再来一次
                    AgainPrize(openid,name);//再来一次
                    result.put("dialCode", "Again"+again);
                } /*else if(rn > 50 && rn <= 60){//百分之20%抽中头盔
                    glove=DialPrize(openid, "Helmet", name);
                    result.put("dialCode", "Helmet");
                }*/ else if(rn > 50 && rn <= 100){//百分之80%抽中手套
                    glove=DialPrize(openid, "Glove", name);
                    result.put("dialCode", "Glove");
                }
            } else {
                glove=DialPrize(openid, "Glove", name);
                result.put("dialCode", "Glove");
            /*    int rn = (int) (Math.random() * 100);
                if (rn <= 20) {//百分之20%抽中头盔
                    glove=DialPrize(openid, "Helmet", name);
                    result.put("dialCode", "Helmet");
                } else {//百分之80%抽中手套
                    glove=DialPrize(openid, "Glove", name);
                    result.put("dialCode", "Glove");
                }*/
            }
            if(glove!=null &&(!StringUtils.isEmpty(glove.getPrizeCode()))){
                result.put("prizeCode",glove.getPrizeCode());
            }
            return getSucceed(result);
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * 领奖用户列表
     * */
    @RequestMapping(value="/api/wxuser/get/prize")
    @LoginAuth(isWx = true)
    public ModelAndView ApiWxGetPrizeList(HttpServletRequest request,HttpServletResponse response){
        SuperRecordModel superRecordModel=new SuperRecordModel();
        superRecordModel.put("prize_flag","1");
        List<SuperRecordModel> list=fPrizeUserService.findPrizeByPrizeFlag(superRecordModel);
        ModelAndView mv=new ModelAndView();
        mv.addObject("prizeList",list);
        mv.setViewName("weixin/prize/getprize");
        return mv;

    }

    /***
     * 用户兑奖页面
     * */
    @RequestMapping(value="/api/wxuser/prize/page")
    @LoginAuth(isWx = true)
    public ModelAndView ApiWxGetPrizePage(HttpServletRequest request,HttpServletResponse response){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("/weixin/prize/valid");
        return mv;
    }

        /**
         * 判断用户是否抽奖
         * */
    private Long exsitPrize(FPrizeUser prizeParam,SuperRecordModel wxInfo){
        prizeParam.setDialType("MarketingDial");//活动类型
        prizeParam.setPrizeFkey(wxInfo.getString("openid"));
        prizeParam.setStatusFlag("1");
        /** blFlag MarketingDial 活动 true 未抽过奖  false 已中奖 **/
        Long countNum = fPrizeUserService.findPrizeCountByParams(prizeParam);
        return countNum;
    }

    public FPrizeUser AgainPrize(String openid,String name){
        FPrizeUser prizeUser = new FPrizeUser();
        prizeUser.setPrizeId(ObjectId.UUID());
        prizeUser.setPrizeFkey(openid);
        prizeUser.setDialType("MarketingDial");//活动类型
        prizeUser.setStatusFlag("0");//再来一次
        prizeUser.setDialCode("Again");
        prizeUser.setDialModule("再来一次");
        prizeUser.setPrizeName(name);
        prizeUser.setStatusTime(new Date());
        fPrizeUserService.insert(prizeUser);
        return prizeUser;
    }

    public FPrizeUser DialPrize(String openid ,String dialCode,String name){
        FPrizeUser prizeUser = new FPrizeUser();
        prizeUser.setPrizeId(ObjectId.UUID());
        prizeUser.setPrizeFkey(openid);
        prizeUser.setDialType("MarketingDial");//活动类型
        prizeUser.setStatusFlag("1");//正常
        prizeUser.setDialCode(dialCode);
        if(dialCode.equals("Helmet")){//头盔
            prizeUser.setDialModule("头盔");
        } else if(dialCode.equals("Glove")){
            prizeUser.setDialModule("手套");
        }
        prizeUser.setPrizeCode(SequenceUtil.Promotion(6));
        prizeUser.setStatusTime(new Date());
        prizeUser.setPrizeFlag("0");//未领取
        prizeUser.setPrizeName(name);
        fPrizeUserService.insert(prizeUser);
        return prizeUser;
    }




}
